import React, { Component, Children } from "react";
import { Tree,message,Button,Modal } from "antd";
import { AllAuthority, UpdateAuthority,UserInfo } from "../../api";
import store from '../../store'
export default class Auth extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      checkedKeys:[],
      username:''
    };
  }
  componentDidMount() {
    AllAuthority().then((res) => {
      var arr = [
        {
          key: "all",
          title: "权限控制",
          children: [],
        }
      ];
      res.forEach((item) => {
        let obj = {};
        obj.key = item._id;
        obj.title = item.title;
        arr[0].children.push(obj);
      });
      this.setState({
        treeData: arr,
      });
    });
   
    UserInfo({uid:store.getState().uid}).then(res=>{
        this.setState({
            checkedKeys:res[0].resource,
            username:res[0].username
        })
    })
  }
  onSubmit = ()=>{
     UpdateAuthority({resource:this.state.checkedKeys,uid:store.getState().uid}).then(res=>{
        if(res){
          Modal.info({
            title: '修改权限成功',
            centered:true
          });
        }
    })
  }
  onCheck = (checkedKeys) => {
    let index = checkedKeys.indexOf('all')
    if (index > -1) {
      checkedKeys.splice(index, 1);
    }
    this.setState({
        checkedKeys
    })
  };
  render() {
    return (
      <div>
        <h1 style={{ textAlign:'left',fontSize:'25px'}}>{this.state.username}的权限</h1>
        <Tree
          checkable
          checkedKeys={this.state.checkedKeys}
          onCheck={this.onCheck}
          treeData={this.state.treeData}
        />
        <Button type="primary" danger style={{ marginLeft:'50px',marginTop:'25px' }} onClick={this.onSubmit} >提交</Button>
      </div>
    );
  }
}
